//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { Button, Card, List } from "antd";
import { useSeaOtterStores } from "../store";
import { PlusOutlined } from "@ant-design/icons";
import type { ImageGroupInfo } from "@/api/seaotter/image_group";
import { list as list_group } from "@/api/seaotter/image_group";
import { get_session } from "@/api/user";
import { request } from "@/utils/request";
import { gen_access_token } from "@/api/project_server";
import EditGroupModal from "./EditGroupModal";

const PAGE_SIZE = 30;

const ImageGroupItem = observer((props: { groupInfo: ImageGroupInfo }) => {
    const appStore = useSeaOtterStores();

    return (
        <div style={{
            cursor: appStore.curImageGroup?.group_name == props.groupInfo.group_name ? "default" : "pointer",
            backgroundColor: appStore.curImageGroup?.group_name == props.groupInfo.group_name ? "#eee" : "white",
            padding: "10px 10px",
            width: "200px",
            fontSize: "16px",
            fontWeight: appStore.curImageGroup?.group_name == props.groupInfo.group_name ? 700 : 500,
        }} onClick={e => {
            e.stopPropagation();
            e.preventDefault();
            appStore.curImageGroup = props.groupInfo;
        }}>
            {props.groupInfo.group_name}
        </div>
    );
});

const ImageGroupList = () => {
    const appStore = useSeaOtterStores();

    const [groupInfoList, setGroupInfoList] = useState<ImageGroupInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const [showCreateModal, setShowCreateModal] = useState(false);

    const loadGroupInfoList = async () => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        const listRes = await request(list_group(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            offset: curPage * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setTotalCount(listRes.total_count);
        setGroupInfoList(listRes.group_list);
        if (appStore.curImageGroup == null && listRes.group_list.length > 0) {
            appStore.curImageGroup = listRes.group_list[0];
        }
    };

    useEffect(() => {
        loadGroupInfoList();
    }, [curPage, appStore.groupDataVersion]);

    return (
        <Card title={<span style={{ fontWeight: 700, fontSize: "18px" }}>镜像分组</span>} bordered={false}
            bodyStyle={{ height: "calc(100vh - 100px)", overflowY: "scroll", padding: "0px 0px" }}
            extra={
                <>
                    {appStore.adminUser && (
                        <Button type="link" icon={<PlusOutlined />} title="创建分组" onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setShowCreateModal(true);
                        }} />
                    )}
                </>
            }>
            <List rowKey="group_name" dataSource={groupInfoList}
                pagination={{ current: curPage + 1, total: totalCount, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), showSizeChanger: false, hideOnSinglePage: true }}
                renderItem={groupInfo => (
                    <List.Item style={{ padding: "0px 0px" }}>
                        <ImageGroupItem groupInfo={groupInfo} />
                    </List.Item>
                )} />
            {showCreateModal == true && (
                <EditGroupModal onCancel={() => setShowCreateModal(false)} onOk={() => {
                    setShowCreateModal(false);
                    if (curPage != 0) {
                        setCurPage(0);
                    } else {
                        loadGroupInfoList();
                    }
                }} />
            )}
        </Card>
    );
};

export default observer(ImageGroupList);